package com.billdowney.qq.robot.plugins.provide;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.billdowney.qq.robot.bean.ConfigBean;
import com.billdowney.qq.robot.plugins.RobotPlugin;
import com.billdowney.qq.robot.plugins.RobotPluginContent;
import com.billdowney.qq.robot.plugins.RobotPluginInfo;
import com.billdowney.qq.robot.util.MessageUtil;
import kotlin.io.FilesKt;
import net.mamoe.mirai.contact.Contact;
import net.mamoe.mirai.contact.Group;
import net.mamoe.mirai.message.data.Image;
import net.mamoe.mirai.utils.BotConfiguration;
import net.mamoe.mirai.utils.RemoteFile;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Collections;
import java.util.List;

/**
 * 媒体插件
 *
 * @author BillDowney
 * @date 2021/4/9 9:45
 */
@Component
public class MediaRobotPlugin implements RobotPlugin, InitializingBean {

    @Autowired
    private ConfigBean configBean;
    /**
     * 图片文件夹
     */
    private File imgFile;
    /**
     * 斗图文件夹
     */
    private File stickerFile;
    /**
     * 短视频文件夹
     */
    private File shortVideoFile;

    @Override
    public void afterPropertiesSet() throws Exception {
        // 媒体文件夹
        File baseMediaPath = FilesKt.resolve(BotConfiguration.getDefault().getWorkingDir(), configBean.getWorkspace() + File.separator + "media" + File.separator);
        this.imgFile = FilesKt.resolve(baseMediaPath, "img");
        this.stickerFile = FilesKt.resolve(baseMediaPath, "sticker");
        this.shortVideoFile = FilesKt.resolve(baseMediaPath, "short_video");
        FileUtil.mkdir(this.imgFile);
        FileUtil.mkdir(this.stickerFile);
        FileUtil.mkdir(this.shortVideoFile);
    }

    @Override
    public RobotPluginInfo info() {
        return RobotPluginInfo.create("媒体插件", false)
                .addDescLn("使用方式：")
                .addDescLn("#看图")
                .addDescLn("#斗图")
                // .addDescLn("#短视频(只支持qq群)")
                .addDescLn("#美图");
    }

    @Override
    public void execute(RobotPluginContent content) {
        if (content.getRobotEventEnum().isMessageEvent()) {
            switch (content.getContent()) {
                case "#看图":
                    File img = this.randomFile(imgFile);
                    if (img == null) {
                        content.putReplyMessage("没有图可以看哦~");
                    } else {
                        Contact contact = null;
                        if (content.getRobotEventEnum().isGroupMsg()) {
                            contact = content.getGroupMessageEvent().getGroup();
                        } else {
                            contact = content.getFriendMessageEvent().getSender();
                        }
                        content.putReplyMessage(contact, MessageUtil.buildImageMessage(contact, img));
                    }
                    break;
                case "#斗图":
                    File sticker = this.randomFile(stickerFile);
                    if (sticker == null) {
                        content.putReplyMessage("没有表情包可以看哦~");
                    } else {
                        Contact contact = null;
                        if (content.getRobotEventEnum().isGroupMsg()) {
                            contact = content.getGroupMessageEvent().getGroup();
                        } else {
                            contact = content.getFriendMessageEvent().getSender();
                        }
                        content.putReplyMessage(contact, MessageUtil.buildImageMessage(contact, sticker));
                    }
                    break;
                case "#短视频":
                    if (content.getRobotEventEnum().isGroupMsg()) {
                        File shortVideo = this.randomFile(shortVideoFile);
                        if (shortVideo == null) {
                            content.putReplyMessage("没有短视频可以看哦~");
                        } else {
                            // 暂时有bug
                            Group group = content.getGroupMessageEvent().getGroup();
                            RemoteFile remoteFile = group.getFilesRoot();
                            content.putReplyMessage(group, remoteFile.resolve(shortVideo.getName()).upload(shortVideo));
                        }
                    }
                    break;
                case "#美图":
                    // TODO 这些api要收费了，暂时考虑不用
//                    List<String> list = Arrays.asList(
//                            // 淘宝买家秀
//                            "rand.tbimg.php"
//                            // 美女
//                            , "rand.img.php?type=%E7%BE%8E%E5%A5%B3"
//                            , "rand.acg.php?type=%E7%BE%8E%E5%A5%B3"
//                            // 性感
//                            , "rand.img.php?type=%E6%80%A7%E6%84%9F"
//                            // 制服
//                            , "rand.img.php?type=%E5%88%B6%E6%9C%8D"
//                            // 二次元
//                            , "rand.acg.php?type=%E4%BA%8C%E6%AC%A1%E5%85%83"
//                            // 呆萌酱
//                            , "rand.acg.php?type=%E5%91%86%E8%90%8C%E9%85%B1"
//                    );
                    List<String> list = Collections.singletonList(
                            "http://img.btu.pp.ua/random/api.php"
                    );
                    this.sendImagesByUrl(content, RandomUtil.randomEle(list));
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 根据url发送图片消息
     *
     * @param content 插件上下文
     * @param url     指向图片的url
     */
    private void sendImagesByUrl(RobotPluginContent content, String url) {
        Contact contact = null;
        if (content.getRobotEventEnum().isGroupMsg()) {
            contact = content.getGroupMessageEvent().getGroup();
        } else {
            contact = content.getFriendMessageEvent().getSender();
        }
        HttpResponse response = HttpRequest.get(url).setFollowRedirects(true).execute();
        Image image = MessageUtil.buildImageMessage(contact, response.bodyStream());
        if (image != null) {
            content.putReplyMessage(contact, image);
        }
    }

    private void sendImagesByKateUrl(RobotPluginContent content, String url) {
        HttpResponse response = HttpRequest.get("https://api.sumt.cn/api/" + url)
                .form("token", configBean.getKateApiToken())
                .form("format", "json")
                .execute();
        Contact contact = null;
        if (content.getRobotEventEnum().isGroupMsg()) {
            contact = content.getGroupMessageEvent().getGroup();
        } else {
            contact = content.getFriendMessageEvent().getSender();
        }
        JSONObject data = JSONUtil.parseObj(response.body());
        if (data.getInt("code") == 200) {
            response = HttpRequest.get(data.getStr("pic_url")).execute();
            Image image = MessageUtil.buildImageMessage(contact, response.bodyStream());
            if (image != null) {
                content.putReplyMessage(contact, image);
            }
        } else {
            content.putReplyMessage(contact, data.getStr("msg"));
        }
    }

    /**
     * 获取一个随机的文件，自动判断是否在文件夹
     *
     * @param file 需要获取的文件夹
     * @return 获取到的文件，可能为null
     */
    private File randomFile(File file) {
        if (file.exists()) {
            if (file.isFile()) {
                return file;
            } else if (file.isDirectory()) {
                File[] imgList = file.listFiles();
                if (imgList != null && imgList.length > 0) {
                    return this.randomFile(RandomUtil.randomEle(imgList));
                }
            }
        }
        return null;
    }

}
